package com.saoft.leaves.controller;

import cn.hutool.crypto.SecureUtil;
import com.saoft.leaves.common.AjaxResult;
import com.saoft.leaves.common.UserConstant;
import com.saoft.leaves.domain.User;
import com.saoft.leaves.service.IUserService;
import com.saoft.leaves.util.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {


    @Autowired
    private IUserService userService;

    /**
     * application.yml 中的配置
     * spring:
     * thymeleaf:
     * prefix: classpath:/templates/
     * suffix: .html
     * <p>
     * return "login" 等于 classpath:/templates/login.html
     *
     * @return
     */
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    /**
     * @return
     * @ResponseBody 代表ajax 请求。没有@ResponseBody 就是跳转页面
     * AjaxResult ajax请求统一规范返回对象。常常包括 code,msg,data 字段
     * code 表示是否成功，msg提示信息，data 返回的数据都放到data中
     */
    @ResponseBody
    @PostMapping("/login")
    public AjaxResult loginPost(String username, String password) {

        if (username == null || username.length() == 0) {
            AjaxResult error = AjaxResult.error();
            error.setMsg("用户名不能为空");
            return error;
        }
        if (password == null || password.length() == 0) {
            AjaxResult error = AjaxResult.error();
            error.setMsg("密码不能为空");
            return error;
        }

        User user = userService.findByUsername(username);

        //浏览器端的密码 md5 加密过后与数据库中比较。
        String md5Password = SecureUtil.md5(password);



        //不等
        if (user==null || !md5Password.equals(user.getPassword())) {
            AjaxResult error = AjaxResult.error();
            error.setMsg("用户名或密码错误");
            return error;
        }

        //将用户信息存入session,可以根据session中的值来判断当前用户是否登录
        HttpSession session = ServletUtils.getSession();
        session.setAttribute(UserConstant.LOGIN_USER, user);

        AjaxResult success = AjaxResult.success();
        success.setMsg("登录成功");
        return success;
    }
}
